package com.ror.java.se.file;

//需求：统计一个文件夹中每种文件的个数并打印（考虑子文件夹）

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

public class Demo07 {
    public static void main(String[] args) {
        File dir = new File("assets", "file");
        HashMap<String, Integer> countMap = count(dir);
        if (countMap == null) {
            System.err.println("没有这样的路径，或路径不是一个目录：" + dir);
            return;
        }
        //map按值排序：转为entry的单列集合排序
        ArrayList<Map.Entry<String, Integer>> countEntries = new ArrayList<>(countMap.entrySet());
        countEntries.sort((e1, e2) -> e1.getValue() - e2.getValue());
        System.out.println(countEntries);
    }

    static HashMap<String, Integer> count(File parent) {
        if (!parent.exists()) return null;
        File[] children = parent.listFiles();
        if (children == null) return null;
        HashMap<String, Integer> countMap = new HashMap<>();
        for (File child : children) {
            if (child.isFile()) {
                String name = child.getName();
                String suffix;
                int index = name.lastIndexOf(".");
                if (index == -1 || index == 0) suffix = "(no-suffix)";
                else suffix = name.substring(index + 1);
                int count = countMap.getOrDefault(suffix, 0);
                countMap.put(suffix, ++count);
            } else countMap.putAll(count(child));
        }
        return countMap;
    }
}
